import fs from 'fs/promises';
import path from 'node:path';
import crypto from 'crypto';

// 阿里云OSS备份类
export class AliyunOSSBackup {
  constructor(config) {
    this.config = config;
    this.endpoint = config.endpoint;
    this.accessKeyId = config.accessKeyId;
    this.accessKeySecret = config.accessKeySecret;
    this.bucket = config.bucket;
    this.region = config.region;
  }

  // 上传文件到OSS
  async uploadFile(localPath, remotePath) {
    try {
      // 这里需要安装阿里云OSS SDK: npm install ali-oss
      const OSS = require('ali-oss');
      
      const client = new OSS({
        region: this.region,
        accessKeyId: this.accessKeyId,
        accessKeySecret: this.accessKeySecret,
        bucket: this.bucket
      });

      const result = await client.put(remotePath, localPath);
      
      return {
        success: true,
        url: result.url,
        etag: result.etag
      };
    } catch (error) {
      console.error('阿里云OSS上传失败:', error);
      throw error;
    }
  }

  // 列出OSS中的备份文件
  async listFiles(prefix = 'backups/') {
    try {
      const OSS = require('ali-oss');
      
      const client = new OSS({
        region: this.region,
        accessKeyId: this.accessKeyId,
        accessKeySecret: this.accessKeySecret,
        bucket: this.bucket
      });

      const result = await client.list({
        prefix: prefix,
        'max-keys': 1000
      });

      return result.objects || [];
    } catch (error) {
      console.error('列出OSS文件失败:', error);
      throw error;
    }
  }

  // 从OSS下载文件
  async downloadFile(remotePath, localPath) {
    try {
      const OSS = require('ali-oss');
      
      const client = new OSS({
        region: this.region,
        accessKeyId: this.accessKeyId,
        accessKeySecret: this.accessKeySecret,
        bucket: this.bucket
      });

      await client.get(remotePath, localPath);
      
      return { success: true };
    } catch (error) {
      console.error('从OSS下载文件失败:', error);
      throw error;
    }
  }

  // 删除OSS文件
  async deleteFile(remotePath) {
    try {
      const OSS = require('ali-oss');
      
      const client = new OSS({
        region: this.region,
        accessKeyId: this.accessKeyId,
        accessKeySecret: this.accessKeySecret,
        bucket: this.bucket
      });

      await client.delete(remotePath);
      
      return { success: true };
    } catch (error) {
      console.error('删除OSS文件失败:', error);
      throw error;
    }
  }
}

// 腾讯云COS备份类
export class TencentCOSBackup {
  constructor(config) {
    this.config = config;
    this.secretId = config.secretId;
    this.secretKey = config.secretKey;
    this.bucket = config.bucket;
    this.region = config.region;
  }

  // 上传文件到COS
  async uploadFile(localPath, remotePath) {
    try {
      // 这里需要安装腾讯云COS SDK: npm install cos-nodejs-sdk-v5
      const COS = require('cos-nodejs-sdk-v5');
      
      const client = new COS({
        SecretId: this.secretId,
        SecretKey: this.secretKey
      });

      const result = await client.uploadFile({
        Bucket: this.bucket,
        Region: this.region,
        Key: remotePath,
        FilePath: localPath
      });

      return {
        success: true,
        url: `https://${result.Location}`,
        etag: result.ETag
      };
    } catch (error) {
      console.error('腾讯云COS上传失败:', error);
      throw error;
    }
  }

  // 列出COS中的备份文件
  async listFiles(prefix = 'backups/') {
    try {
      const COS = require('cos-nodejs-sdk-v5');
      
      const client = new COS({
        SecretId: this.secretId,
        SecretKey: this.secretKey
      });

      const result = await new Promise((resolve, reject) => {
        client.getBucket({
          Bucket: this.bucket,
          Region: this.region,
          Prefix: prefix,
          MaxKeys: 1000
        }, (err, data) => {
          if (err) reject(err);
          else resolve(data);
        });
      });

      return result.Contents || [];
    } catch (error) {
      console.error('列出COS文件失败:', error);
      throw error;
    }
  }

  // 从COS下载文件
  async downloadFile(remotePath, localPath) {
    try {
      const COS = require('cos-nodejs-sdk-v5');
      
      const client = new COS({
        SecretId: this.secretId,
        SecretKey: this.secretKey
      });

      await new Promise((resolve, reject) => {
        client.getObject({
          Bucket: this.bucket,
          Region: this.region,
          Key: remotePath,
          OutputPath: localPath
        }, (err, data) => {
          if (err) reject(err);
          else resolve(data);
        });
      });
      
      return { success: true };
    } catch (error) {
      console.error('从COS下载文件失败:', error);
      throw error;
    }
  }

  // 删除COS文件
  async deleteFile(remotePath) {
    try {
      const COS = require('cos-nodejs-sdk-v5');
      
      const client = new COS({
        SecretId: this.secretId,
        SecretKey: this.secretKey
      });

      await new Promise((resolve, reject) => {
        client.deleteObject({
          Bucket: this.bucket,
          Region: this.region,
          Key: remotePath
        }, (err, data) => {
          if (err) reject(err);
          else resolve(data);
        });
      });
      
      return { success: true };
    } catch (error) {
      console.error('删除COS文件失败:', error);
      throw error;
    }
  }
}

// 云备份管理器
export class CloudBackupManager {
  constructor(config) {
    this.config = config;
    this.provider = config.provider; // 'aliyun' 或 'tencent'
    
    if (this.provider === 'aliyun') {
      this.client = new AliyunOSSBackup(config.aliyun);
    } else if (this.provider === 'tencent') {
      this.client = new TencentCOSBackup(config.tencent);
    } else {
      throw new Error(`不支持的云存储提供商: ${this.provider}`);
    }
  }

  // 上传备份到云端
  async uploadBackup(localPath, filename) {
    try {
      const remotePath = `backups/${filename}`;
      const result = await this.client.uploadFile(localPath, remotePath);
      
      // 保存上传记录
      await this.saveUploadRecord(filename, remotePath, result);
      
      return {
        success: true,
        remotePath: remotePath,
        url: result.url,
        etag: result.etag
      };
    } catch (error) {
      console.error('上传备份到云端失败:', error);
      throw error;
    }
  }

  // 从云端下载备份
  async downloadBackup(remotePath, localPath) {
    try {
      const result = await this.client.downloadFile(remotePath, localPath);
      return result;
    } catch (error) {
      console.error('从云端下载备份失败:', error);
      throw error;
    }
  }

  // 列出云端备份
  async listCloudBackups() {
    try {
      const files = await this.client.listFiles('backups/');
      const records = await this.getUploadRecords();
      
      // 合并文件信息和上传记录
      const backups = files.map(file => {
        const record = records.find(r => r.remotePath === file.Key);
        return {
          filename: path.basename(file.Key),
          remotePath: file.Key,
          size: file.Size,
          lastModified: file.LastModified,
          etag: file.ETag,
          uploadTime: record?.uploadTime || file.LastModified,
          url: record?.url || null
        };
      });

      return backups.sort((a, b) => new Date(b.uploadTime) - new Date(a.uploadTime));
    } catch (error) {
      console.error('列出云端备份失败:', error);
      return [];
    }
  }

  // 删除云端备份
  async deleteCloudBackup(remotePath) {
    try {
      await this.client.deleteFile(remotePath);
      await this.deleteUploadRecord(remotePath);
      
      return { success: true };
    } catch (error) {
      console.error('删除云端备份失败:', error);
      throw error;
    }
  }

  // 保存上传记录
  async saveUploadRecord(filename, remotePath, uploadResult) {
    try {
      const recordsFile = path.resolve(process.cwd(), './backups/cloud_uploads.json');
      let records = [];
      
      try {
        const content = await fs.readFile(recordsFile, 'utf-8');
        records = JSON.parse(content);
      } catch {
        // 文件不存在，使用空数组
      }
      
      const record = {
        filename,
        remotePath,
        url: uploadResult.url,
        etag: uploadResult.etag,
        uploadTime: new Date().toISOString(),
        provider: this.provider
      };
      
      records.push(record);
      await fs.writeFile(recordsFile, JSON.stringify(records, null, 2));
    } catch (error) {
      console.error('保存上传记录失败:', error);
    }
  }

  // 获取上传记录
  async getUploadRecords() {
    try {
      const recordsFile = path.resolve(process.cwd(), './backups/cloud_uploads.json');
      const content = await fs.readFile(recordsFile, 'utf-8');
      return JSON.parse(content);
    } catch {
      return [];
    }
  }

  // 删除上传记录
  async deleteUploadRecord(remotePath) {
    try {
      const recordsFile = path.resolve(process.cwd(), './backups/cloud_uploads.json');
      let records = [];
      
      try {
        const content = await fs.readFile(recordsFile, 'utf-8');
        records = JSON.parse(content);
      } catch {
        return;
      }
      
      records = records.filter(record => record.remotePath !== remotePath);
      await fs.writeFile(recordsFile, JSON.stringify(records, null, 2));
    } catch (error) {
      console.error('删除上传记录失败:', error);
    }
  }
}
